# -*- coding:utf-8 -*-

import os

from src.package_helper.pkg_helper import PkgHelperInterface
from src.utils import runcmd
from src.core import macro
from src.utils.logger import logger
from src.core.global_config import GlobalConfig

RPM_NAMES = "openEuler-latest-release"
SPEC_NAMES = "openEuler-latest-release.spec"


class PkgLatestReleaseHelper(PkgHelperInterface):
    _vendor_src = None
    _product_name = None
    _version_id = None

    def __init__(self, vendor_src, product_name, version_id, version_info):
        self._spec_names = SPEC_NAMES
        self._vendor_src = vendor_src
        self._product_name = product_name
        self._version_id = version_id
        self._version_info = version_info
        runcmd.rpm_src_setup(vendor_src + "/" + RPM_NAMES + "*")

    def replace_vendor(self):
        self._replace_spec()
        self._replace_source()

    def _replace_spec(self):
        logger.warning("begin replace latest_release vendor")
        _spec = macro.RPM_SRC_SETUP_SPEC_PATH + self._spec_names
        runcmd.replace(_spec, "openEuler", "%{product_name}")
        runcmd.replace(_spec, "openeuler", "%{product_name}")
        runcmd.replace(_spec, "BuildRoot:", "Provides:        openEuler-latest-release\nBuildRoot:", 1)
        _data = runcmd.read_file(_spec)
        _data = macro.ADDTION_HEAD_LINE + _data
        runcmd.rewrite_file(_spec, _data)

    def _replace_source(self):
        current_path = os.path.abspath(__file__)
        package_helper_path = os.path.dirname(current_path)
        src_path = os.path.dirname(package_helper_path)
        project_path = os.path.dirname(src_path)
        if os.path.exists(macro.RPM_SRC_SETUP_SOURCE_PATH + "/isopackage.sdf") is False:
            isopackage_path = project_path + "/isopackage.sdf"
            isopackage_dst_path = macro.RPM_SRC_SETUP_SOURCE_PATH + "/isopackage.sdf"
            runcmd.cp_file(isopackage_path, isopackage_dst_path)
        if os.path.exists(macro.RPM_SRC_SETUP_SOURCE_PATH + "/isopackage_arm64.sdf") is False:
            isopackage_path = project_path + "/isopackage_arm64.sdf"
            isopackage_dst_path = macro.RPM_SRC_SETUP_SOURCE_PATH + "/isopackage_arm64" \
                                                                    ".sdf"
            runcmd.cp_file(isopackage_path, isopackage_dst_path)
        for root, dirs, files in os.walk(macro.RPM_SRC_SETUP_SOURCE_PATH):
            for f in files:
                if f.startswith("isopackage") is True:
                    file = os.path.join(root, f)
                    runcmd.replace(file, "openEuler", self._product_name)
                    runcmd.replace(file, "openeuler", self._product_name)
                    runcmd.replace(file, GlobalConfig.BASE_ISO_VERSION, self._version_info)

    def replace_rpm(self):
        pass

